package com.gnrsoft.rpc.server;

import java.lang.reflect.Method;
import java.util.Map;

import com.gnrsoft.rpc.common.RpcRequest;
import com.gnrsoft.rpc.common.RpcResponse;

import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class RpcHandler extends ChannelInboundHandlerAdapter {

	private Map<String, Object> handlerMap;

	public RpcHandler(Map<String, Object> handlerMap) {
		this.handlerMap = handlerMap;
	}

	/**
	 * 
	 * <B>方法名称：接受客户端消息，处理请求</B><BR>
	 * 
	 * @see io.netty.channel.ChannelInboundHandlerAdapter#channelRead(io.netty.channel.ChannelHandlerContext,
	 *      java.lang.Object)
	 */
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

		
		RpcResponse response = new RpcResponse();
		try {
			response.setResult(handle((RpcRequest) msg));
		} catch (Exception e) {
			response.setError(e);
		}
		//返回调用结果给客户端，且关闭这次连接
		ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
		
		

	}
	//执行业务逻辑
	private Object handle(RpcRequest msg) throws Exception {

		String className = msg.getClassName();
		Object serviceBean = handlerMap.get(className);
		String methodName = msg.getMethodName();
		Class<?>[] parameterTypes = msg.getParameterTypes();
		Object[] parameters = msg.getParameters();
		Class<?> forName = Class.forName(className);
		Method method = forName.getMethod(methodName, parameterTypes);
		
		return method.invoke(serviceBean, parameters);
	}
	
	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.printStackTrace();
		ctx.close();
		
	}

}
